
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const multer = require('multer');
const fs = require('fs-extra');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 文件上传配置
const upload = multer({ dest: 'uploads/' });

// 机器人状态数据
let robotStatus = {
  battery: 85,
  temperature: 25,
  volume: 60,
  motionMode: '待机',
  wifiConnected: true,
  aiConnected: false
};

// 舞步文件存储
let danceFiles = [];

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('客户端已连接:', socket.id);
  
  // 发送初始状态
  socket.emit('robotStatus', robotStatus);
  
  // 监听配置更新
  socket.on('updateConfig', (config) => {
    console.log('收到配置更新:', config);
    // 这里可以添加与ESP32通信的逻辑
    socket.emit('configUpdated', config);
  });
  
  // 监听控制命令
  socket.on('controlCommand', (command) => {
    console.log('收到控制命令:', command);
    // 这里可以添加与ESP32通信的逻辑
    socket.emit('commandExecuted', command);
  });
  
  // 监听舞步执行
  socket.on('executeDance', (danceName) => {
    console.log('执行舞步:', danceName);
    robotStatus.motionMode = `执行中: ${danceName}`;
    io.emit('robotStatus', robotStatus);
  });
  
  socket.on('disconnect', () => {
    console.log('客户端已断开连接:', socket.id);
  });
});

// API 路由
app.get('/api/status', (req, res) => {
  res.json(robotStatus);
});

app.post('/api/config', (req, res) => {
  const config = req.body;
  console.log('更新配置:', config);
  // 这里可以添加与ESP32通信的逻辑
  res.json({ success: true, message: '配置已更新' });
});

app.post('/api/control', (req, res) => {
  const command = req.body;
  console.log('控制命令:', command);
  // 这里可以添加与ESP32通信的逻辑
  res.json({ success: true, message: '命令已执行' });
});

// 舞步文件上传
app.post('/api/upload-dance', upload.single('danceFile'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '没有上传文件' });
  }
  
  const fileInfo = {
    name: req.file.originalname,
    size: req.file.size,
    uploadTime: new Date().toISOString(),
    path: req.file.path
  };
  
  danceFiles.push(fileInfo);
  res.json({ success: true, file: fileInfo });
});

// 获取舞步文件列表
app.get('/api/dances', (req, res) => {
  res.json(danceFiles);
});

// 模拟机器人状态更新
setInterval(() => {
  // 随机更新一些状态值
  robotStatus.battery = Math.max(0, robotStatus.battery - Math.random() * 0.1);
  robotStatus.temperature = 20 + Math.random() * 10;
  robotStatus.volume = 30 + Math.random() * 40;
  
  io.emit('robotStatus', robotStatus);
}, 5000);

server.listen(PORT, () => {
  console.log(`Otto DIY Web 控制台运行在 http://localhost:${PORT}`);
});
